package com.panshi.controller;

import com.panshi.config.JWTUtils;
import com.panshi.config.MailUtils;
import com.panshi.service.IAdminLoginService;
import com.panshi.tools.AdminLogin;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import redis.clients.jedis.Jedis;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@Controller
// 跨域
@CrossOrigin
public class AdminLoginController {
    @Autowired
    private IAdminLoginService iAdminLoginService;
    String token = null;
    private int sjs=0;
    //获取当前用户
    //1. 获取连接
    Jedis jedis = new Jedis("localhost",6379);
    /***
     * 登录请求
     * @param adminMail
     * @param password
     * @param model
     * @return
     * @throws IOException
     * @throws ServletException
     */
    @RequestMapping("/adminLogin")
    @ResponseBody
    public Map login(String adminMail, String password  , Model model) throws IOException, ServletException {
        log.error("登录请求 userLogin");
        HttpServletRequest request   = ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest();
        HttpServletResponse response  = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getResponse();
        //获取当前用户
        Subject subject = SecurityUtils.getSubject();
        Map<String,Object> map = new HashMap<>();
        // 封装用户的登陆数据
        UsernamePasswordToken tokens = new UsernamePasswordToken(adminMail,password);
        try {
            AdminLogin adminLogin = iAdminLoginService.queryAdminByAdminName(adminMail);
            Cookie cook = new Cookie("AdminMail",adminLogin.getAdminMail());
            cook.setPath("/");
            Cookie cooks = new Cookie("AdminId",adminLogin.getAdminId()+"");
            cooks.setPath("/");
            response.addCookie(cook);
            response.addCookie(cooks);
            Map<String,String> payload = new HashMap<>();
            payload.put("id",adminLogin.getAdminId()+"");
            payload.put("userMail", adminLogin.getAdminMail());
            String token = JWTUtils.getToken(payload);
//            //执行登录方法
            subject.login(tokens);
            map.put("state",true);
            map.put("mag","登录成功");
            map.put("token",token);
            log.error("用户登录成功");
            return map;

        } catch (UnknownAccountException uae) {
            map.put("state",false);
            map.put("mag","用户名不存在");
            map.put("token",token);
            log.error("用户名不存在");
            return map;
        } catch (IncorrectCredentialsException ice) {
            map.put("state",false);
            map.put("mag","密码错误");
            map.put("token",token);
            log.error("密码错误");
            return map;
        } catch (LockedAccountException lae) {
            map.put("state",false);
            map.put("mag","用户被锁定");
            map.put("token",token);
            log.error("用户被锁定");
            return map;
        }catch (AuthenticationException ae) {
            map.put("state",false);
            map.put("mag","登录失败");
            map.put("token",token);
            log.error("登录失败");
            return map;
        }
    }

    /***
     * 忘记密码请求
     * @return
     */
    @RequestMapping("/userForgetPassword")
    @ResponseBody
    public Map forgetPassword(String adminMail, String password  , String meilYzm, Model model) throws IOException, ServletException {
        log.error("忘记密码 userRegister" +adminMail);
        log.error("忘记密码  password" +password);
        log.error("忘记密码  meilYzm" +meilYzm);

        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        HttpServletResponse response = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getResponse();
//        request.setCharacterEncoding("UTF-8");
//        response.setCharacterEncoding("UTF-8");
//        response.setHeader("Content-type","text/html;charset=UTF-8");
        Map<String,Object> map = new HashMap<>();
        AdminLogin adminLogin = iAdminLoginService.queryAdminByAdminName(adminMail);
        AdminLogin admin = new AdminLogin();
        String meil = jedis.get(adminMail);
        log.error("meil       "+meil);
        if(meil == null){
            map.put("state",false);
            map.put("mag","验证码已过期或暂未获取验证码，请重新获取！！");
            map.put("token",null);
            log.error("验证码已过期或暂未获取验证码，请重新获取！！");
            return map;
        }
        if(!meil.equals(meilYzm)){
            map.put("state",false);
            map.put("mag","邮箱验证码有误");
            map.put("token",null);
            log.error("邮箱验证码有误");
            return map;
        }
        if(adminLogin == null){
            map.put("state",false);
            map.put("mag","当前邮箱不存在账号");
            map.put("token",null);
            log.error("当前邮箱不存在账号");
            return map;
        }
        admin.setAdminMail(adminMail);
        admin.setPassword(password);
        iAdminLoginService.forgetAdminPassword(admin);
        Cookie cook = new Cookie("AdminMail",adminLogin.getAdminMail());
        cook.setPath("/");
        Cookie cooks = new Cookie("AdminId",adminLogin.getAdminId()+"");
        cooks.setPath("/");
        response.addCookie(cook);
        response.addCookie(cooks);
        map.put("state",false);
        map.put("mag","修改密码成功");
        map.put("token",null);
        log.error("修改密码成功");
        return map;
    }

    @PostMapping("/QQ")
    @ResponseBody
    public void qq(String adminMail ){
        log.error("发送QQ邮箱验证码请求 QQ");
        for(int j = 0; j< 100; j++) {
            sjs = (int) ((Math.random() * 9 + 1) * 100000);
        }
        // 存进Redis
        jedis.set(adminMail,sjs+"");
        jedis.expire(adminMail, 90);
        try {
            /**
             * @param email 收件人的邮箱地址
             * @param subject 邮件主题
             * @param emailMsg 邮件内容
             */
            log.error(adminMail);
            log.error("sjs 随机数 ： "+sjs);
            MailUtils.sendMail(adminMail,"有贝口腔","【有贝口腔】尊敬的用户，您的验证码："+sjs+"，切勿将验证码泄露于他人。");

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

